import { Inject, Injectable } from '@nestjs/common';

import { CreateLoginDto, LoginDto } from './dto/create-login.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { UserService } from '../user/user.service';
import { encryption, jwtConstants } from 'src/utils/tool';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class LoginService {
  @Inject()
  private readonly prismaService: PrismaService;

  @Inject()
  private readonly user: UserService;

  @Inject()
  private readonly jwtService: JwtService;

  //注册
  async create(createLoginDto: CreateLoginDto) {
    const { username, password, email, nickName, phone } = createLoginDto;
    // 判断用户名是否存在
    const userExist = await this.prismaService.user.findFirst({
      where: {
        username,
      },
    })
    if (userExist) {
      return {
        message: '用户名已存在'
      }
    }
    const user = await this.prismaService.user.create({
      data: {
        username,
        email,
        nickName,
        phone,
        password: encryption(password),
        avatar: 'https://img1.baidu.com/it/u=1333417867,4012964063&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1714496400&t=acbd289a0ec893e2560c39246a0d35b2',
      },
    })
    // 初始化用户角色
    // 通过角色名称查询角色id
    const role = await this.prismaService.role.findFirst({
      where: {
        name: "普通用户"
      }
    })
    await this.prismaService.userRole.create({
      data: {
        userId: user.id,
        roleId: role.id,
      },
    })
    delete user.password;
    delete user.id;
    return user;
  }

  //登录
  async login(loginDto: LoginDto,) {
    const { username, password } = loginDto;
    const user = await this.prismaService.user.findFirst({
      where: {
        username,
      },
    })
    if (user && user.password === encryption(password)) {
      delete user.password;
      delete user.id;
      return {
        token: this.jwtService.sign(user, {
          secret: jwtConstants.secret,
        }),
      }
    } else {
      return {
        message: '账号或密码错误'
      }
    }
  }
}
